import React, { Component, Suspense } from "react";
import { connect } from "dva";
import {
	Popconfirm,
	Table,
	Drawer,
	Form,
	Button,
	Col,
	Row,
	Input,
	Select,
	DatePicker,
	Icon,
	message,
	Radio,
	Modal,
	Tag,
	Pagination,
	Spin,
	Switch,
} from "antd";
import styles from "./typeNode.less";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import Answer from "./answer";
import SimilarQuestion from "./similarQuestion";
import GuideEdit from "@/pages/KnowledgeGraph/editDrawer/guideEdit";
import { node } from "prop-types";
import QuoteAnswer from "@/pages/KnowledgeGraph/editDrawer/quoteAnswer";
import UserSession from "@/UserSession";
import axios from "axios";

const { Search, TextArea } = Input;
const { Option } = Select;
const FormItem = Form.Item;
const getItems = (count) =>
	Array.from({ length: count }, (v, k) => k).map((k) => ({
		id: `item-${k}`,
		content: `item ${k}`,
	}));
const getListStyle = (isDraggingOver) => ({
	background: isDraggingOver ? "lightblue" : "#fff",
	display: "flex",
	padding: 8,
	overflow: "auto",
});
const reorder = (list, startIndex, endIndex) => {
	const result = Array.from(list);
	const [removed] = result.splice(startIndex, 1);
	result.splice(endIndex, 0, removed);

	return result;
};

const grid = 8;
const getItemStyle = (isDragging, draggableStyle) => ({
	// some basic styles to make the items look a bit nicer
	userSelect: "none",
	padding: 11,
	margin: `0 8px 0 0`,
	color: "grey",
	borderRadius: "30px",
	border: "1px solid lightgray",
	lineHeight: "0px",
	cursor: "move",
	// change background colour if dragging
	background: isDragging ? "lightgreen" : "#fefe",

	// styles we need to apply on draggables
	...draggableStyle,
});

class Intentions extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			node: {},
			knowledgeType: 1,
			page: 1,
			limit: 10,
			keys: "",
			modalTitle: "",
			placeholder: "请输入已有词槽",
			type: "slot",
			list: [],
			total: 0,
			addLoading: false,
			showModal: false,
			isAddApi: false,
			isAddSlot: false,
			apiObj: [],
			isShowApiTag: true,
			apiId: "",
			slotArr: [],
			apiNames: "",
			apiDataSource: [],
			count: 1,
			items: getItems(6),
			drawWidth: 720,
			mindData: {
				id: "0",
				label: "引导话术",
				nodeType: "root",
				children: [],
			},
			similarQuestions: [],
			similarQuestion: "",
			isNew: true,
			qaId: props.qaId ? props.qaId : "",
			relateQAs: [],
			standardQus: "",
			atlasExplain: "",
			atlasTitle: "",
			similarTotal: 0,
			similarPage: 1,
			classVisible: false,
			classField: "q",
			linkTotal: 0,
			classPage: 1,
			searchClass: "",
			relateList: [],
			similarSearch: "",
			allSimilarData: [],
			slotTotal: "",
			quoteAnswerShow: false,
			quoteAnswerPage: 1,
			quoteAnswer: {
				list: [],
				total: 0,
				page: 1,
			},
			quoteAnswerObj: null,
			addAnswerType: 0,
			qaStatus: true,
			isSensitive: false,
			treeData: [],
			quoteAnswerParam: {
				query: "",
				page: 1,
				limit: 10,
				categoryId: "root",
				queryType: "question",
				sortType: "updateTime",
				robotId: props.currentUser.robotId,
				isNoneAnswer: "false",
			},
			isSystem: true,
			graphDetail: null,
		};
	}

	onDragEnd(result) {
		if (!result.destination) {
			return;
		}
		const items = reorder(
			this.state.slotArr,
			result.source.index,
			result.destination.index
		);
		this.setState({
			slotArr: items,
		});
	}

	componentDidMount() {
		this.initKnow(this.props.node.qaId);
		this.getQuoteAnswer();
		this.getCategoryTree();
		const { visible, node } = this.props;
		if (visible) {
			this.setState({
				visible,
				node,
			});
		}
	}

	componentWillReceiveProps(nextProps, nextContext) {
		const { visible } = nextProps;
		const { node } = nextProps;
		if (node) {
			this.setState({ node });
		}
		if (visible) {
			this.setState({
				visible,
			});
		}
	}

	showDrawer = () => {
		this.setState({ visible: true });
	};

	onClose = () => {
		this.setState({ visible: false });
		if (this.props.close) {
			this.props.close(this.state.qaId);
		}
	};

	initKnow = (qaId) => {
		// this.getCategoryListJson();
		if (qaId && qaId != undefined) {
			this.setState(
				{
					qaId,
					isNew: false,
				},
				() => {
					this.getAnswerDetailByQaid(qaId);
					this.getQuestionsByQaid(qaId);
					this.getStandardQuestionByQaId(qaId);
				}
			);
		} else {
			this.setState(
				{
					isNew: true,
				},
				() => {
					// this.getQaIdByReq();
				}
			);
		}
	};

	getGuid = () => {
		const { dispatch, node } = this.props;
		const { nodes } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/processGuide",
				payload: { atlasId: node.atlas_id, atlasNodesId: node._id },
				callback: (res) => {
					let data = res[0];
					let that = this;
					data.nodeColor = that.getNodeColor(data);
					that.getNodeData(data.children);
					this.setState({ mindData: res[0] });
				},
			});
		});
	};

	getNodeData = (data) => {
		let that = this;
		for (let i = 0; i < data.length; i++) {
			data[i].nodeColor = that.getNodeColor(data[i]);
			if (data[i].nodeType == 2) {
				data[i].fontColor = "red";
				data[i].borderColor = "red";
			}
			if (data[i].children.length > 0) {
				that.getNodeData(data[i].children);
			}
		}
	};

	getNodeColor = (node) => {
		if (node.nodeType === 0) {
			return "#0099FF";
		}
		if (node.nodeType === 1) {
			return "#66CC66";
		}
		if (node.nodeType === 2) {
			return "#fff";
		}
	};

	resetNodeName = (data) => {
		let dataArr = [];
		for (item of data) {
			let dataJson = {
				id: item._id,
				label: item.processName,
				nodeType: item.processType,
				children: item.children,
				isDel: item.isDel,
				atlasNodesId: item.atlasNodesId,
				parentId: item.parentId,
			};
			dataArr.push(dataJson);
		}
		return dataArr;
	};

	getAnswerDetailByQaid = (qaId) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getKnowledgeDetail",
				payload: {
					id: qaId,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					if (res.apiId) {
						this.getApiDetailByApiId(res.apiId);
					}
					this.setState(
						{
							// apiObj: res.api,
							apiId: res.apiId,
							slotArr: res.slotList,
							atlasExplain: res.atlasExplain,
							atlasTitle: res.atlasTitle,
							isAddSlot:
								!res.slotList === true ? false : res.slotList.length > 0,
							isAddApi: !res.apiId !== true,
							apiDataSource: res.slotAndApi,
							isShard: res.shared,
							synchronous: !res.synchronous === true ? false : res.synchronous,
							knowledgeType: parseInt(res.atlasKnowledgeType),
							relateList: !res.relateList === true ? [] : res.relateList,
							isSystem: res.relateQaSource && res.relateQaSource == 1 ? false : true,
							relateQAs: !res.relateList === true ? [] : res.relateQAs,
							drawWidth: parseInt(res.atlasKnowledgeType) == 1 ? 720 : 1000,
							isSensitive: res.isSensitive === 1 ? true : false,
							qaStatus: !res.disabled,
							graphDetail: res,
						},
						() => {
							if (this.state.knowledgeType == 2) {
								this.getGuid();
							}
							this.getJsonAnswerByQaId(this.state.qaId);
						}
					);
				},
			});
		});
	};

	getJsonAnswerByQaId = (id) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getAnswer",
				payload: {
					qaId: id,
					isShared: this.state.shared,
					isSynchronous: this.state.synchronous,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					for (const i of res) {
						i.isEdit = true;
					}
					if (res.length === 0) {
						res.push({
							isDefault: true,
							content: "",
							answerType: "richText",
							slotValues: [],
							isEdit: false,
						});
					}
					this.Answer.getAnswer(res);
					// this.setState({
					//   spinning: false,
					//   answerArr: res,
					//   answerArr_bak: res,
					// });
				},
			});
		});
	};

	getQuestionsByQaid = (qaId, isTowDrawer) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getAlikeQuestionList",
				payload: {
					id: qaId,
					limit: 999999,
					page: 1,
					h: this.state.similarSearch,
					efix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					const arr = [];
					for (const i of res.list) {
						arr.push(i.question);
					}
					this.setState(
						{
							allSimilarData: arr,
							similarTotal: res.total,
						},
						() => {
							this.pageData();
						}
					);
				},
			});
		});
	};

	pageData = () => {
		const {
			similarTotal,
			similarPage,
			similarQuestions,
			allSimilarData,
		} = this.state;
		let minIndex = similarPage * 10 - 10;
		let maxIndex = similarPage * 10;
		let currenArr = [];
		let allData = allSimilarData;
		for (let i = minIndex; i < maxIndex; i++) {
			if (allData[i]) {
				currenArr.push(allData[i]);
			}
		}
		this.setState({
			similarQuestions: currenArr,
		});
	};

	getStandardQuestionByQaId = (qaId) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getStandardQuestion",
				payload: {
					id: qaId,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					this.setState({
						standardQus: res.question,
					});
				},
			});
		});
	};

	getQaIdByReq = () => {
		const { dispatch } = this.props;
		const obj = {};
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getQaId",
				payload: {
					...obj,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					this.setState({
						qaId: res.qaId,
					});
				},
			});
		});
	};

	saveNode() {
		const form = this.props.form;
		let {
			apiDataSource,
			apiId,
			knowledgeType,
			node,
			isNew,
			relateQAs,
			relateList,
			allSimilarData,
		} = this.state;
		let nodes = node;
		// let questionList = this.state.similarQuestions;
		let relateIdArr = [];
		console.log(relateList);
		for (let i of relateList) {
			relateIdArr.push(i.sid ? i.sid : i.id);
		}
		relateQAs = relateIdArr;

		// let questionList = this.state.allSimilarData;
		let questionList = [];

		form.validateFields((err, values) => {
			if (err) {
				return false;
			}
			//答案
			let answerArr = this.Answer.state.answerArr;
			let conContent = this.Answer.state.conRefs;
			const answerSource = this.Answer.state.isSystem ? 0 : 1;
			//词槽
			const slotIdArr = [];

			if (knowledgeType === 1) {
				//普通知识点
				// 词槽和请求字段对应关系
				if (apiDataSource.length > 0) {
					let flog = false;
					for (const i of apiDataSource) {
						delete i.key;
						Object.keys(i).map((keyItem, j) => {
							if (i[keyItem] === "") {
								flog = true;
								switch (keyItem) {
									case "slotKey":
										return message.error(
											"词槽和请求字段对应关系中词槽不可为空"
										);
										break;
									case "apiFieldId":
										return message.error(
											"词槽和请求字段对应关系中请求字段不可为空"
										);
										break;
								}
							}
						});
					}
					if (flog) {
						return false;
					}
				}
				//词槽
				for (const i of this.state.slotArr) {
					if (i.id) {
						slotIdArr.push(i.id);
					} else {
						slotIdArr.push(i._id);
					}
				}
				//答案
				for (let i = 0; i < answerArr.length; i++) {
					if (!answerArr[i].isEdit) {
						if (!answerArr[i].answerType !== "text") {
							// answerArr[i].content = conContent[i].getUeditorContent();
							answerArr[i].content = this.Answer.AnswerEdit.refs[
								`content${i}`
							].getUeditorContent();
						} else {
						}
					}
				}
			} else {
			}
			//流程引导
			let graphNode = {};
			if (this.mindRef) {
				if (this.mindRef.graphNode) {
					graphNode = this.mindRef.graphNode.graph.save();
				}
			}
			// questionList.unshift(values.ask);
			questionList.push(values.ask);
			questionList = questionList.concat(allSimilarData);
			const { dispatch } = this.props;
			let obj = {};
			if (knowledgeType == 1) {
				obj = {
					answers: answerArr,
					answerSource,
					slots: slotIdArr,
					slotAndApi: apiDataSource,
					apiId: apiId,
					atlasId: nodes.atlas_id,
					atlasNodeId: nodes._id,
					qaId: this.state.qaId,
					questions: questionList,
					atlasTitle: values.title,
					atlasExplain: values.dis,
					atlasKnowledgeType: knowledgeType,
					isNew,
					isSharedQA: false,
					categoryId: "/",
					isForever: true,
					relateQAs: relateQAs,
					relateQaSource: this.state.isSystem ? null : 1,
					disabled: !this.state.qaStatus,
					isSensitive: this.state.isSensitive ? 1 : 0,
				};
			} else {
				obj = {
					answers: null,
					slots: null,
					slotAndApi: null,
					apiId: null,
					atlasId: nodes.atlas_id,
					atlasNodeId: nodes._id,
					qaId: this.state.qaId,
					questions: questionList,
					atlasTitle: values.title,
					atlasExplain: values.dis,
					atlasKnowledgeType: knowledgeType,
					isNew,
					isSharedQA: false,
					categoryId: "/",
					isForever: true,
					relateQAs: relateQAs,
					relateQaSource: this.state.isSystem ? null : 1,
					graphNode,
					disabled: !this.state.qaStatus,
					isSensitive: this.state.isSensitive ? 1 : 0,
				};
			}

			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "intentionsList/saveQA",
					payload: obj,
					callback: (res) => {
						message.info(res.msg);
						this.setState(
							{
								relateQAs: [],
								saveQaLoading: false,
							},
							() => {
								let type = "";
								if (knowledgeType == 3) {
									type = 1;
								}

								if (knowledgeType == 2) {
									type = 3;
								}

								if (knowledgeType == 1) {
									type = 2;
								}
								this.props.close(values.title, res.data, type);
							}
						);
					},
				});
			});
		});
	}

	changeType = (e) => {
		if (e.target.value === 2) {
			this.setState({ drawWidth: 1000 });
			this.getGuid();
		} else {
			this.setState({ drawWidth: 720 });
		}
		this.setState({ knowledgeType: e.target.value });
	};
	showModal = (type) => {
		this.setState(
			{
				showModal: true,
				addLoading: true,
				type,
			},
			() => {
				switch (type) {
					case "api":
						this.fetchApiListByRobotId();
						break;
					case "slot":
						this.fetchSlotListByRobotId();
						break;
				}
			}
		);
	};
	fetchApiListByRobotId = (page) => {
		const { dispatch, currentUser } = this.props;
		let newPage = this.state.page;
		const newLimit = this.state.limit;
		const newApiNames = this.state.apiNames;
		if (page) {
			newPage = page;
		}

		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/fetchApi",
				payload: {
					robotId: currentUser.robotId,
					page: newPage,
					limit: newLimit,
					apiNames: newApiNames,
				},
				callback: (res) => {
					this.setState({
						modalTitle: "添加API接口",
						placeholder: "请输入已有API接口",
						type: "api",
						list: res.list,
						slotTotal: res.total,
						addLoading: false,
					});
				},
			});
		});
	};

	fetchSlotListByRobotId = (page) => {
		const { dispatch, currentUser } = this.props;
		let newPage = this.state.page;
		const newLimit = this.state.limit;
		const newKeys = this.state.keys;
		if (page) {
			newPage = page;
		}

		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/fetchSlot",
				payload: {
					robotId: currentUser.robotId,
					page: newPage,
					limit: newLimit,
					keys: newKeys,
				},
				callback: (res) => {
					this.setState({
						modalTitle: "添加词槽",
						placeholder: "请输入已有词槽",
						type: "slot",
						list: res.list,
						slotTotal: res.total,
						addLoading: false,
					});
				},
			});
		});
	};

	modalSearch = (val) => {
		const type = this.state.type;
		this.setState({ searchType: type }, () => {
			switch (type) {
				case "api":
					this.setState({ apiNames: val }, () => {
						this.fetchApiListByRobotId(1);
					});
					break;
				case "slot":
					this.setState({ keys: val }, () => {
						this.fetchSlotListByRobotId(1);
					});
					break;
			}
		});
	};

	selected(item) {
		const type = this.state.type;
		switch (type) {
			case "api":
				this.setState(
					{
						isAddApi: true,
						apiObj: item,
						showModal: false,
						isShowApiTag: true,
						apiId: item.id,
					},
					() => {
						this.getApiDetailByApiId(item.id);
					}
				);
				break;
			case "slot":
				const arr = this.state.slotArr;
				if (arr.length >= 5) {
					return message.error("词槽不可大于5个，请删除重试");
				}

				const result = arr.some((items) => {
					return items.name == item.name;
				});
				if (result) {
					return message.error("该词槽已存在");
				}
				arr.push(item);
				this.setState({
					isAddSlot: true,
					showModal: false,
					slotArr: arr,
				});
				break;
		}
	}

	getApiDetailByApiId = (id) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/fetchApiDetailById",
				payload: {
					apiId: id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					this.setState(
						{
							apiObj: res,
						},
						() => {}
					);
				},
			});
		});
	};

	handleCancel() {
		this.setState({ showModal: false, page: 1, classPage: 1 });
	}

	delSlot = (e, index, name, ids) => {
		e.preventDefault();
		const arr = this.Answer.state.answerArr_bak;
		const slotList = this.state.slotArr;
		const slotDetailArr = this.Answer.state.slotDetailArr;
		for (const i of arr) {
			for (const j of i.slotValues) {
				if (j.slotName === name) {
					return message.error("该词槽被下面的答案引用，请删除/修改答案后尝试");
				}
			}
		}
		slotList.splice(index, 1);
		const newSlotDetailArr = slotDetailArr.filter((item) => item.id !== ids);
		this.Answer.setSlotDetailArr(newSlotDetailArr);
		this.setState({
			slotArr: slotList,
		});
	};
	handleAdd = () => {
		const { slotArr, apiObj } = this.state;
		if (slotArr.length === 0) {
			return message.error("请先添加词槽");
		}

		const { apiDataSource, count } = this.state;
		const newData = {
			key: count,
			slotKey: "",
			apiFieldId: "",
		};
		this.setState({
			apiDataSource: [...apiDataSource, newData],
			count: count + 1,
		});
	};
	handleDelete = (key) => {
		const dataSource = [...this.state.apiDataSource];
		this.setState({
			apiDataSource: dataSource.filter((item) => item.key !== key),
		});
	};
	fixData = (e, record, type) => {
		const { apiDataSource } = this.state;
		for (const i of apiDataSource) {
			if (i.key === record.key) {
				switch (type) {
					case "apiFieldId":
						i.apiFieldId = e;
						break;
					case "slotKey":
						i.slotKey = e;
						break;
				}
			}
		}
		this.setState({
			apiDataSource,
		});
	};
	cleanApi = (e) => {
		e.preventDefault();
		this.setState({
			apiObj: {},
			isShowApiTag: false,
			isAddApi: false,
			apiId: "",
		});
	};

	showChildrenDrawer = () => {
		// const { qaId } = this.props;
		this.setState({
			childrenDrawer: true,
			isShowSimTitle: false,
			drawerLoading: false,
			isTowDrawer: true,
		});
	};

	onCloseChildren = () => {
		this.setState(
			{
				allSimilarData: this.SimilarQuestion.state.moreQuestionList,
			},
			() => {
				this.setState({ childrenDrawer: false });
			}
		);
	};

	addQuestion(data) {
		let similarArr = this.state.allSimilarData;
		similarArr.unshift(data);
		this.setState({ allSimilarData: similarArr }, () => {
			this.pageData();
		});
	}

	remove(index, e) {
		let similarArr = this.state.allSimilarData;
		similarArr = similarArr.filter((key) => key !== e);
		this.setState({ allSimilarData: similarArr });
	}

	changeIndex(index) {
		let similarArr = this.state.allSimilarData;
		similarArr[index - 1] = similarArr.splice(
			index,
			1,
			similarArr[index - 1]
		)[0];
		this.setState({ allSimilarData: similarArr });
	}

	changeSimilarItem(data) {
		let index = data.index;
		let val = data.val;
		let similarArr = this.state.allSimilarData;
		similarArr[index] = val;
		if (this !== data) {
			this.setState({ allSimilarData: similarArr });
		}
	}

	addSlotToSmQuestion(data) {
		let index = data.index;
		let nowIndex = (this.state.similarPage - 1) * 10 + index;
		let similarArr = this.state.allSimilarData;
		similarArr[nowIndex] = data.value;
		this.setState({ allSimilarData: similarArr }, () => {
			this.pageData();
		});
	}

	addLinkQa = () => {
		this.setState({
			classVisible: true,
		});
		this.fetchLinkData();
	};
	fetchLinkData = () => {
		this.setState(
			{
				loading: true,
			},
			() => {
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "intentionsList/linkBoxJson",
						payload: {
							robotId: currentUser.robotId,
							question: this.state.standardQus,
							field: this.state.classField,
							query: this.state.searchClass,
							page: this.state.classPage,
							limit: 10,
						},
						callback: (res) => {
							const arr = res.qaList;
							const suggestionsLength = res.suggestList.length;
							this.setState({
								linkTotal: res.total,
								linkData: arr,
								loading: false,
								suggestionsLength,
							});
						},
					});
				});
			}
		);
	};
	pageChange = (num) => {
		this.setState(
			{
				similarPage: num,
				drawerLoading: false,
			},
			() => {
				this.pageData();
			}
		);
	};
	classSelectChange = (e) => {
		this.setState(
			{
				classField: e,
				classPage: 1,
			},
			() => {
				this.fetchLinkData();
			}
		);
	};
	fanye(e, a) {
		const type = this.state.type;
		if (a) {
			this.setState(
				{
					classPage: e,
				},
				() => {
					return this.fetchLinkData();
				}
			);
		}
		switch (type) {
			case "api":
				this.setState(
					{
						page: e,
					},
					() => {
						this.fetchApiListByRobotId();
					}
				);
				break;
			case "slot":
				this.setState(
					{
						page: e,
					},
					() => {
						this.fetchSlotListByRobotId();
					}
				);
				break;
		}
	}
	searchClass = (e) => {
		this.setState(
			{
				searchClass: e,
				classPage: 1,
			},
			() => {
				this.fetchLinkData();
			}
		);
	};
	addLinkThis = (item) => {
		let arr = [];
		let relateArr = [];
		arr = arr.concat(this.state.relateQAs);
		if (arr.length >= 10) {
			return message.error("关联问最多添加10条");
		}
		arr.unshift(item.sid);
		relateArr = relateArr.concat(this.state.relateList);
		relateArr.unshift(item);
		this.setState(
			{
				relateQAs: arr,
				relateList: relateArr,
			},
			() => {}
		);
	};
	classHandleCancel = () => {
		this.setState({
			classVisible: false,
			searchClass: "",
			classPage: 1,
			page: 1,
		});
	};
	onDelRelateQa = (index, qa) => {
		const arr = this.state.relateList;
		const { relateQAs } = this.state;
		for (let i = 0; i < relateQAs.length; i++) {
			if (relateQAs[i] === qa.id) {
				relateQAs.splice(i, 1);
			}
		}
		arr.splice(index, 1);
		this.setState({
			relateList: arr,
			relateQAs,
		});
	};
	onSetRelateQa = (index) => {
		const arr = this.state.relateList;
		if (index !== 0) {
			arr[index] = arr.splice(index - 1, 1, arr[index])[0];
		} else {
			arr.push(arr.shift());
		}
		this.setState({
			relateList: arr,
		});
	};
	getQusBySearch = (val) => {
		this.setState(
			{
				similarSearch: val,
				similarPage: 1,
			},
			() => {
				this.getQuestionsByQaid(this.state.qaId);
			}
		);
	};
	newCreate = () => {
		const type = this.state.type;
		switch (type) {
			case "api":
				window.open("/knowledgeDesign/customApi");
				break;
			case "slot":
				window.open("/knowledgeDesign/wordTroughManage");
				break;
		}
	};

	hideQuoteAnswer = () => {
		let { quoteAnswerParam } = this.state;
		quoteAnswerParam.categoryId = "root";
		quoteAnswerParam.query = "";
		quoteAnswerParam.page = 1;
		this.setState(
			{
				quoteAnswerParam,
				quoteAnswerShow: false,
			},
			() => {
				this.getQuoteAnswer();
			}
		);
	};

	showQuoteAnswer = (type) => {
		this.setState({
			quoteAnswerShow: true,
			addAnswerType: type,
		});
	};

	handleQuoteAnswerChange = (value) => {
		let { quoteAnswerPage, quoteAnswerParam } = this.state;
		quoteAnswerParam.page = value;
		this.setState(
			{
				quoteAnswerPage: value,
				quoteAnswerParam,
			},
			() => {
				this.getQuoteAnswer();
			}
		);
	};

	getCategoryTree = () => {
		const { dispatch } = this.props;
		const obj = {};
		const headData = {
			"Content-Type": "application/json",
			Authorization: `Bearer ${UserSession.getToken()}`,
		};
		return new Promise((resolve) => {
			axios
				.post("/knowledge-api/answerCategory/getCategoryTree", obj, {
					headers: headData,
				})
				.then((res) => {
					const arr = [];
					if (res.data.data) {
						arr.push(res.data.data[0]);
						this.setState({
							treeData: arr,
						});
					}
				});
		});
		// dispatch({
		//   type: 'intentionsList/categoryListJson',
		//   payload: obj,
		//   callback: res => {
		//     let arr = [];
		//     if (res) {
		//       arr.push(res[0]);
		//       this.setState({
		//         treeData: arr,
		//       });
		//     }
		//   },
		// });
	};

	queryAnswerByCondition = (value, flag) => {
		let { quoteAnswer, quoteAnswerParam } = this.state;
		const that = this;
		if (flag === 1) {
			quoteAnswerParam.categoryId = value;
		} else {
			quoteAnswerParam.query = value;
		}
		quoteAnswerParam.page = 1;
		that.setState(
			{
				quoteAnswerParam,
			},
			() => {
				that.getQuoteAnswer();
			}
		);
	};

	getQuoteAnswer = () => {
		const { dispatch } = this.props;
		let { quoteAnswer, quoteAnswerParam } = this.state;
		dispatch({
			type: "intentionsList/getQuoteAnswer",
			payload: quoteAnswerParam,
			callback: (res) => {
				console.log(res);
				this.setState({
					quoteAnswer: res,
				});
			},
		});
	};

	selectQuoteAnswer = (item) => {
		const { addAnswerType } = this.state;
		this.setState({ quoteAnswerObj: item }, () => {
			this.hideQuoteAnswer();
			if (addAnswerType == 0) {
				this.Answer.setAnswer({ robotAnswers: item, answersHeadquarters: null, answerSource: null });
			} else {
				this.mindRef.setAnswer(item.answer);
			}
		});
	};

	//敏感/非敏感
	onChangeSensitive = (value) => {
		this.setState({ isSensitive: value });
	};

	//启用/禁用
	onChangeQaStatus = (value) => {
		this.setState({ qaStatus: value });
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		const {
			node, apiDataSource, apiObj, drawWidth, similarQuestions, standardQus,
			atlasTitle, atlasExplain, allSimilarData, isSystem, graphDetail,
		} = this.state;
		const formItemLayout = {
			labelCol: {
				xs: { span: 26 },
				sm: { span: this.state.knowledgeType == 1 ? 4 : 2 },
			},
			wrapperCol: {
				xs: { span: 22 },
				sm: { span: 20 },
			},
		};
		const formItemLayoutWithOutLabel = {
			wrapperCol: {
				xs: { span: 22, offset: 4 },
				sm: { span: 20, offset: this.knowledgeType == 1 ? 4 : 2 },
			},
		};
		const slotList = this.state.slotArr;
		for (let i of slotList) {
			if (i.id) {
				i._id = i.id;
			}
		}
		const apiColumns = [
			{
				title: "词槽",
				dataIndex: "slotKey",
				width: "30%",
				render: (text, record) =>
					slotList.length >= 1 ? (
						<Select
							defaultValue='选择词槽'
							value={text}
							style={{ width: 200 }}
							onChange={(e) => this.fixData(e, record, "slotKey")}>
							{slotList.map((slot, index) => {
								return <Option value={slot.key}>&lt;{slot.name}&gt;</Option>;
							})}
						</Select>
					) : null,
			},
			{
				title: "API字段-请求字段",
				dataIndex: "apiFieldId",
				render: (text, record) => (
					<Select
						defaultValue='选择API请求字段'
						value={text}
						style={{ width: 200 }}
						onChange={(e) => this.fixData(e, record, "apiFieldId")}>
						{apiObj.requestFields
							? apiObj.requestFields.map((api, index) => {
									return <Option value={api.id}>#{api.name}#</Option>;
							  })
							: null}
					</Select>
				),
			},
			{
				title: "操作",
				dataIndex: "operation",
				render: (text, record) =>
					this.state.apiDataSource.length >= 1 ? (
						<Popconfirm
							title='确认删除该列吗？'
							onConfirm={() => this.handleDelete(record.key)}>
							<Button
								type='primary'
								size='small'
								icon='delete'
								htmlType='button'>
								{" "}
								删除
							</Button>
						</Popconfirm>
					) : null,
			},
		];
		this.columns = [
			{
				title: "问题",
				key: "question",
				dataIndex: "question",
			},
			{
				title: "分类",
				key: "category",
				dataIndex: "category",
			},
			{
				title: "操作",
				render: (text, item) => {
					return (
						<div>
							{this.state.relateQAs.indexOf(item.sid) === -1 ? (
								<Button
									htmlType='button'
									type='primary'
									size='small'
									onClick={(text) => {
										this.addLinkThis(item);
									}}
									icon='link'>
									关联{" "}
								</Button>
							) : (
								<Button htmlType='button' size='small' icon='link'>
									已关联{" "}
								</Button>
							)}
						</div>
					);
				},
			},
		];
		return (
			<div>
				<Drawer
					title={node ? node.nodeName : ""}
					width={drawWidth}
					onClose={this.onClose}
					visible={this.state.visible}
					bodyStyle={{ paddingBottom: 80 }}>
					<Form>
						<Form.Item label='知识点类型' {...formItemLayout}>
							<Radio.Group
								onChange={this.changeType}
								value={this.state.knowledgeType}>
								<Radio value={1}>普通知识点</Radio>
								{/*<Radio value={2}>流程引导知识点</Radio>*/}
							</Radio.Group>
							{/*{this.state.knowledgeType === 1 ? (*/}
							{/*  <div>*/}
							{/*    <Row>*/}
							{/*      <Button style={{ marginRight: 10 }} onClick={() => this.showModal('api')}>*/}
							{/*        添加API接口*/}
							{/*      </Button>*/}
							{/*      <Button onClick={() => this.showModal('slot')}>添加词槽</Button>*/}
							{/*    </Row>*/}
							{/*  </div>*/}
							{/*) : (*/}
							{/*  ''*/}
							{/*)}*/}
						</Form.Item>
						{this.state.knowledgeType === 1 ? (
							<div>
								{this.state.isAddSlot ? (
									<div style={{ marginTop: 10 }}>
										<div className={styles.label}>词槽</div>
										<DragDropContext onDragEnd={this.onDragEnd.bind(this)}>
											<Droppable droppableId='droppable' direction='horizontal'>
												{(provided, snapshot) => (
													<div
														ref={provided.innerRef}
														style={getListStyle(snapshot.isDraggingOver)}
														{...provided.droppableProps}>
														{slotList.map((item, index) => (
															<Draggable
																key={item._id}
																draggableId={item._id}
																index={index}>
																{(provided, snapshot) => (
																	<div
																		ref={provided.innerRef}
																		{...provided.draggableProps}
																		{...provided.dragHandleProps}
																		style={getItemStyle(
																			snapshot.isDragging,
																			provided.draggableProps.style
																		)}>
																		&lt;{item.name}&gt;-{item.key}
																		<Icon
																			type='close'
																			onClick={(e) =>
																				this.delSlot(
																					e,
																					index,
																					item.name,
																					item._id
																				)
																			}
																			style={{
																				marginLeft: 10,
																				cursor: "pointer",
																				color: "#000",
																			}}
																		/>
																	</div>
																)}
															</Draggable>
														))}
														{provided.placeholder}
													</div>
												)}
											</Droppable>
										</DragDropContext>
									</div>
								) : (
									""
								)}
							</div>
						) : (
							""
						)}
						{this.state.knowledgeType === 1 ? (
							<div>
								{this.state.isAddApi ? (
									<div style={{ marginTop: 10 }}>
										<div className={styles.label}>API接口</div>
										<div className={styles.labelWarp}>
											<span>触发知识点时调用接口</span>
											{this.state.isShowApiTag ? (
												<span>
													<Tag
														closable
														className={styles.apiTag}
														onClose={this.cleanApi}>
														{this.state.apiObj.name}
													</Tag>
													<Icon
														style={{ marginLeft: 10 }}
														onClick={() => this.showModal("api")}
														type='edit'
													/>
												</span>
											) : (
												""
											)}
										</div>
										<p style={{ color: "grey", paddingLeft: 10 }}>
											词槽与字段的对应关系
										</p>
										<Table
											bordered
											rowKey='key'
											size='small'
											pagination={false}
											columns={apiColumns}
											dataSource={apiDataSource}
										/>
										<Button
											onClick={this.handleAdd}
											type='primary'
											size='small'
											icon='plus'
											style={{ marginTop: 16 }}>
											{" "}
											添加
										</Button>
									</div>
								) : (
									""
								)}
							</div>
						) : (
							""
						)}
						<div>
							<div className={styles.label}>基础设置</div>
							<Form.Item label='标题' {...formItemLayout}>
								{getFieldDecorator("title", {
									initialValue: atlasTitle ? atlasTitle : node.nodeName,
									rules: [{ required: true, message: "标题不能为空" }],
								})(
									<Input
										style={{ width: "88%" }}
										placeholder='标题'
										className={styles.inputItem}
									/>
								)}
							</Form.Item>
							<Form.Item label='说明' {...formItemLayout}>
								{getFieldDecorator("dis", {
									initialValue: atlasExplain ? atlasExplain : "",
								})(
									<TextArea
										style={{ width: "88%" }}
										placeholder='说明'
										className={styles.inputItem}
									/>
								)}
							</Form.Item>
							<Form.Item label='是否启用' {...formItemLayout}>
								{getFieldDecorator("qaStatus", {
									initialValue: this.state.qaStatus
										? this.state.qaStatus
										: false,
								})(
									<Switch
										checkedChildren='启用'
										unCheckedChildren='禁用'
										checked={this.state.qaStatus}
										onChange={this.onChangeQaStatus}
									/>
								)}
							</Form.Item>
							{/* <Form.Item label='敏感状态' {...formItemLayout}>
								{getFieldDecorator("isSensitive", {
									initialValue: this.state.isSensitive
										? this.state.isSensitive
										: false,
								})(
									<Switch
										checkedChildren='敏感'
										unCheckedChildren='非敏感'
										checked={this.state.isSensitive}
										onChange={this.onChangeSensitive}
									/>
								)}
							</Form.Item> */}
							<div className={styles.label}>问题</div>
							<Form.Item label='标准问' {...formItemLayout}>
								{getFieldDecorator("ask", {
									initialValue: standardQus ? standardQus : "",
									rules: [{ required: true, message: "标准问必填" }],
								})(
									<Input
										style={{ width: "88%" }}
										placeholder='请添加标准问'
										className={styles.inputItem}
									/>
								)}
							</Form.Item>
							<SimilarQuestion
								slotList={slotList}
								onRef={(ref) => {
									this.SimilarQuestion = ref;
								}}
								keys={this.state.knowledgeType ? this.state.knowledgeType : 1}
								seeMore={() => this.showChildrenDrawer()}
								isShowMore={similarQuestions.length > 6}
								similarQuestions={
									this.state.qaId && !this.state.isNew
										? allSimilarData
										: allSimilarData
								}
								// similarQuestions={similarQuestions}
								addQuestion={this.addQuestion.bind(this)}
								remove={this.remove.bind(this)}
								changeIndex={this.changeIndex.bind(this)}
								changeSimilarItem={this.changeSimilarItem.bind(this)}
								addSlotToSmQuestion={this.addSlotToSmQuestion.bind(this)}
								knowledgeType={this.state.knowledgeType}
							/>
						</div>
						<div>
							<Row style={{ margin: "10px 0px" }}>
								<Col span={4}>
									<div className={styles.label}>关联问题</div>
								</Col>
								<Col span={20} style={{ textAlign: 'right' }}>
									{UserSession.isSystemKnowledge() ? null : (
										<Button
											// disabled={this.state.synchronous && this.state.shared}
											type='primary'
											size='small'
											onClick={() => this.addLinkQa()}
										>
											添加关联知识点
										</Button>
									)}
								</Col>
							</Row>
							{this.state.relateList.map((qa, qaIndex) => {
								return (
									<Form.Item {...formItemLayoutWithOutLabel} key={qaIndex}>
										<div>
											<Input
												value={qa.question}
												key={qaIndex}
												disabled
												style={{ width: "88%" }}
											/>
											<span>
												{UserSession.isSystemKnowledge() && isSystem ? null : (
													<Icon
														className='dynamic-delete-button'
														type='close-circle'
														onClick={() => this.onDelRelateQa(qaIndex, qa)}
														style={{
															fontSize: 20,
															marginLeft: 10,
															cursor: "pointer",
															marginTop: 5,
														}}
													/>
												)}
												{UserSession.isSystemKnowledge() && isSystem ? null : qaIndex > 0 ? (
													<Icon
														type='arrow-up'
														onClick={() => this.onSetRelateQa(qaIndex)}
														style={{
															fontSize: 20,
															marginLeft: 10,
															cursor: "pointer",
															marginTop: 5,
														}}
													/>
												) : (
													""
												)}
											</span>
										</div>
									</Form.Item>
								);
							})}
						</div>
						<div
							style={{
								display: this.state.knowledgeType == 1 ? "block" : "none",
							}}>
							<Answer
								slotArr={this.state.slotArr}
								props={this.props}
								onRef={(ref) => {
									this.Answer = ref;
								}}
								answer={this.state.quoteAnswerObj}
								onShow={this.showQuoteAnswer}></Answer>
						</div>
						{this.state.knowledgeType == 1 ? (
							""
						) : (
							<div>
								<GuideEdit
									data={this.state.mindData}
									onRef={(r) => (this.mindRef = r)}
									onClose={this.getGuid}
									add={this.showQuoteAnswer}
								/>
							</div>
						)}
						{/* {this.state.knowledgeType == 1 ? (
							<div>
								<Answer
									slotArr={this.state.slotArr}
									props={this.props}
									onRef={ref => {
										this.Answer = ref;
									}}
								></Answer>
							</div>
						) : (
							<GuideEdit data={this.state.mindData} onRef={r => (this.mindRef = r)} onClose={this.getGuid} />
						)} */}
					</Form>
					<Modal
						visible={this.state.showModal}
						title={this.state.modalTitle}
						onCancel={this.handleCancel.bind(this)}
						footer={[
							<Pagination
								defaultCurrent={1}
								limit={10}
								onChange={(e) => this.fanye(e)}
								total={parseInt(this.state.slotTotal)}
								size='small'
								current={this.state.page}
							/>,
						]}
						width={350}
						key={123}
						centered>
						<div>
							<Search
								placeholder={this.state.placeholder}
								onSearch={(value) => this.modalSearch(value, 1)}
								style={{ width: 200 }}
							/>
							<Button
								htmlType='button'
								style={{ marginLeft: 10 }}
								onClick={() => this.newCreate()}>
								新建
							</Button>
						</div>
						<div className={styles.modalBody}>
							<Spin spinning={this.state.addLoading}>
								{this.state.list.map((api, index) => {
									return (
										<div className={styles.modalItem} key={api.name}>
											<Button
												htmlType='button'
												size='small'
												type='primary'
												onClick={() => this.selected(api)}>
												{" "}
												选择
											</Button>
											{this.state.type === "api" ? (
												<span style={{ marginLeft: 10 }}>{api.name}</span>
											) : (
												<span style={{ marginLeft: 10 }}>
													&lt;{api.key}&gt; ({api.name})
												</span>
											)}
										</div>
									);
								})}
							</Spin>
						</div>
					</Modal>
					<div
						style={{
							position: "absolute",
							right: 0,
							bottom: 0,
							width: "100%",
							borderTop: "1px solid #e9e9e9",
							padding: "10px 16px",
							background: "#fff",
							textAlign: "right",
							zIndex: 99999999,
						}}>
						<Button onClick={this.onClose} style={{ marginRight: 8 }}>
							取消
						</Button>
						<Button onClick={this.saveNode.bind(this)} type='primary'>
							保存
						</Button>
					</div>
					<Drawer
						title='返回'
						width={720}
						visible={this.state.childrenDrawer}
						bodyStyle={{ paddingBottom: 80 }}
						onClose={this.onCloseChildren.bind(this)}
						destroyOnClose>
						<SimilarQuestion
							slotList={slotList}
							onRef={(ref) => {
								this.SimilarQuestion = ref;
							}}
							isShowMore={false}
							isTowDrawer={this.state.isTowDrawer}
							similarQuestions={allSimilarData}
							addQuestion={this.addQuestion.bind(this)}
							remove={this.remove.bind(this)}
							changeIndex={this.changeIndex.bind(this)}
							changeSimilarItem={this.changeSimilarItem.bind(this)}
							addSlotToSmQuestion={this.addSlotToSmQuestion.bind(this)}
							getQusBySearch={this.getQusBySearch.bind(this)}
							knowledgeType={this.state.knowledgeType}
						/>
					</Drawer>
					<Modal
						visible={this.state.classVisible}
						title='选择关联问题'
						onCancel={this.classHandleCancel}
						footer={[]}
						width={750}
						key='2'
						centered>
						<Form layout='inline' style={{ paddingBottom: 20 }}>
							<FormItem>
								<Select
									style={{ width: 160 }}
									defaultValue={this.state.classField}
									onChange={this.classSelectChange}>
									<Option value='q'>搜索问题</Option>
									<Option value='a'>搜索答案</Option>
								</Select>
							</FormItem>
							<FormItem>
								<Search
									placeholder='请输入内容'
									onSearch={(value) => this.searchClass(value)}
									style={{ width: 320 }}
									allowClear
								/>
							</FormItem>
						</Form>
						<Spin spinning={this.state.loading}>
							<Table
								style={{ height: 500, overflow: "auto" }}
								size='small'
								columns={this.columns}
								dataSource={this.state.linkData} // 数据
								rowKey='sid'
								pagination={{
									// 分页
									total: parseInt(this.state.linkTotal), // 数据总数量
									pageSize: 10,
									onChange: (e) => this.fanye(e, 1),
									showQuickJumper: true,
									current: this.state.classPage,
								}}
							/>
						</Spin>
					</Modal>
				</Drawer>
				{this.state.quoteAnswerShow ? (
					<QuoteAnswer
						visible={this.state.quoteAnswerShow}
						onCannel={this.hideQuoteAnswer}
						onSelect={this.selectQuoteAnswer}
						answer={this.state.quoteAnswer}
						handleQuoteAnswer={this.handleQuoteAnswerChange}
						page={this.state.quoteAnswerPage}
						treeData={this.state.treeData}
						queryAnswer={this.queryAnswerByCondition}
					/>
				) : (
					""
				)}
			</div>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(Intentions));
